package com.designpattern.singleton;

import java.io.*;

/**
 * 静态内部类单例模式
 */
public class InnerClassSingletonTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
//        InnerClassSingleton innerClassSingleton = InnerClassSingleton.getInnerClassSingleton();
//        InnerClassSingleton innerClassSingleton1 = InnerClassSingleton.getInnerClassSingleton();
//        System.out.println(innerClassSingleton);
//        System.out.println(innerClassSingleton1);

//        new Thread(()->{
//            InnerClassSingleton innerClassSingleton = InnerClassSingleton.getInnerClassSingleton();
//            System.out.println(innerClassSingleton);
//        }).start();
//        new Thread(()->{
//            InnerClassSingleton innerClassSingleton = InnerClassSingleton.getInnerClassSingleton();
//            System.out.println(innerClassSingleton);
//        }).start();

        InnerClassSingleton innerClassSingleton = InnerClassSingleton.getInnerClassSingleton();
//        ObjectOutputStream outputStream=new ObjectOutputStream(new FileOutputStream("testSerializable"));
//        outputStream.writeObject(innerClassSingleton);
//        outputStream.close();

        ObjectInputStream inputStream=new ObjectInputStream(new FileInputStream("testSerializable"));
        InnerClassSingleton object = (InnerClassSingleton) inputStream.readObject();
        System.out.println(innerClassSingleton == object);
    }

}

class InnerClassSingleton implements Serializable {

   static final long serialVersionUID = 42L;

    private InnerClassSingleton(){}

    private static class InnerClassHolder{
        private  static InnerClassSingleton innerClassSingleton=new InnerClassSingleton();

    }
    public static InnerClassSingleton getInnerClassSingleton(){
        return InnerClassHolder.innerClassSingleton;
    }

    Object readResolve() throws ObjectStreamException{
        return InnerClassHolder.innerClassSingleton;
    }
}